
package cn.edu.swu.miniwebsvr.core;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpParser {

    public static Parameter parse(InputStream inputStream) throws IOException {
        Parameter parameter = new Parameter();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

        /* ========== 1. 请求行 ========== */
        String requestLine = reader.readLine();
        if (requestLine == null || requestLine.isEmpty()) throw new IOException("Empty request line");
        String[] parts = requestLine.split(" ");
        if (parts.length < 3) throw new IOException("Invalid request line");
        parameter.setMethod(parts[0]);

        String fullUrl = parts[1];
        String urlPath;
        int qIdx = fullUrl.indexOf('?');
        if (qIdx != -1) {
            urlPath = fullUrl.substring(0, qIdx);
            String query = fullUrl.substring(qIdx + 1);
            decodeParams(query, parameter.getUrlParams());
        } else {
            urlPath = fullUrl;
        }
        parameter.setUrl(urlPath);


        String line;
        while ((line = reader.readLine()) != null && !line.isEmpty()) {
            int colon = line.indexOf(':');
            if (colon != -1) {
                parameter.getHeaders().put(line.substring(0, colon).trim(), line.substring(colon + 1).trim());
            }
        }


        if ("POST".equalsIgnoreCase(parameter.getMethod())) {
            int contentLen = 0;
            String lenStr = parameter.getHeaders().get("Content-Length");
            if (lenStr != null) {
                try { contentLen = Integer.parseInt(lenStr); } catch (NumberFormatException ignore) { }
            }
            if (contentLen > 0) {
                char[] bodyChars = new char[contentLen];
                reader.read(bodyChars);
                String body = new String(bodyChars);
                String type = parameter.getHeaders().get("Content-Type");
                if (type != null && type.contains("application/x-www-form-urlencoded")) {
                    decodeParams(body, parameter.getBodyParams());
                }
            }
        }

        return parameter;
    }

    // TODO: [222024321072054/李欣雨] 可以添加辅助方法来简化字符串解析和 URL 解码
    private static void decodeParams(String query, Map<String, String> map) {
        if (query == null || query.isEmpty()) return;
        String[] pairs = query.split("&");
        for (String pair : pairs) {
            String[] kv = pair.split("=", 2);
            String key = urlDecode(kv[0]);
            String val = kv.length > 1 ? urlDecode(kv[1]) : "";
            map.put(key, val);
        }
    }

    private static String urlDecode(String s) {
        try { return URLDecoder.decode(s, StandardCharsets.UTF_8.name()); }
        catch (Exception e) { return s; }
    }
}